<?php

/**
 * BaseController
 * @property	User	$user
 */
class BaseController {
	protected $user;
	public function __construct(Request $request, Response $response, $method) {
		if (!$this->loginCheck()) {
			if (!in_array($method, ['login', 'resetPassword'])) $response->redirect('/session/login/');
		} else {
			$this->user = User::load($_COOKIE['_uid']);
			if ($this->user->type == User::TYPE_ADMINISTRATOR && !in_array($request->path(0), ['admin', 'session'])) $response->redirect('/admin/');
		}
	}
	protected function loginCheck() {
		/**
		 * @var	User	$user
		 */
		if (!($user = User::load(isset($_COOKIE['_uid'])? $_COOKIE['_uid'] : '0'))) return false;
		if (!isset($_COOKIE['_secret']) || $_COOKIE['_secret'] != md5($user->id .'_ebf_'. $user->password)) {
			$this->clearCookie();
			return false;
		}
		return true;
	}
	protected function clearCookie() {
		setcookie("_uid", '', time(), '/', ADMIN_HOST);
		setcookie("_uid", '', time(), '/', '*.'.ADMIN_HOST);
		setcookie("_secret", '', time(), '/', ADMIN_HOST);
		setcookie("_secret", '', time(), '/', '*.'.ADMIN_HOST);
	}
}